import 'package:countdown/common/model/EventRecord.dart';
import 'package:get/get.dart';
import 'package:isar/isar.dart';

import '../../common/services/services.dart';
import 'index.dart';

class ListController extends GetxController {
  //页面状态
  final state = ListState();

  ListController();

  //刷新
  void onRefresh() async {
    await asyncLoadAllData();
  }

  final isar = IsarDatabaseService.to.isar();

  // 拉取分页数据
  asyncLoadAllData() async {
    final eventRecords = await isar.eventRecords
        .where()
        .filter()
        .ifArchiveEqualTo(false)
        .sortBySortDesc()
        .offset(0)
        .limit(50)
        .findAll();
    state.eventRecords = eventRecords;
  }

  ///交换sort字段并更新数据库
  Future<void> onReorder(int oldIndex, int newIndex) async {
    //需要更新数据库 1.根据id查出两条数据.交换sort字段
    int? temp = 0;
    EventRecord oldEventRecord = state.eventRecords[newIndex];
    EventRecord newEventRecord = state.eventRecords[oldIndex];
    temp = oldEventRecord.sort;
    //新对象复制给老的
    oldEventRecord.sort = newEventRecord.sort;
    //老的复制给新的
    newEventRecord.sort = temp;

    // 修改数据
    await isar.writeTxn(() async {
      await isar.eventRecords.put(newEventRecord);
      await isar.eventRecords.put(oldEventRecord);
    });

    // //返回删除的值
    // EventRecord eventRecord = state.eventRecords.removeAt(oldIndex);
    // //查到原来的位置
    // state.eventRecords.insert(newIndex, eventRecord);
    onRefresh();
  }

  ///删除数据
  Future<void> delete(int id) async {
    // 修改数据
    await isar.writeTxn(() async {
      await isar.eventRecords.delete(id);
    });
    onRefresh();
  }

  @override
  void onReady() {
    asyncLoadAllData();
  }
}
